<template>
  <view class="address_">
    <view class="form_wrapper">
      <u-picker
        mode="region"
        v-model="pickerShow"
        @confirm="regionConfirm"
        :area-code="areaCode"
        :default-region="defaultRegion"
      ></u-picker>
      <u-form :model="formData" ref="uForm" label-width="150">
        <u-form-item label="收货人" prop="consigneeName">
          <u-input v-model="formData.consigneeName" />
        </u-form-item>
        <u-form-item label="联系电话" prop="consigneeMobile">
          <u-input v-model="formData.consigneeMobile" :type="'number'" />
        </u-form-item>
        <u-form-item
          label="所在地区"
          prop="consigneeProvince"
          class="positioning_wrapper"
        >
          <view class="content_">
            <!--            <u-input v-model="formData.intro" @click.stop="show = true" disabled="true"/>-->
            <u-input
              type="select"
              :select-open="pickerShow"
              v-model="model.region"
              placeholder="省、市、区"
              @click="pickerShow = true"
            ></u-input>
            <!--            <view class="img_wrapper" @tap="chooseLocation">-->
            <!--              <image src="/static/address/1.png"></image>-->
            <!--              <text>定位</text>-->
            <!--            </view>-->
          </view>
        </u-form-item>
        <u-form-item label="详细地址" prop="consigneeAddress" class="positioning_wrapper">
          <view class="content_">
            <u-input
              v-model="formData.consigneeAddress"
              placeholder="请填写具体地址"
            ></u-input>
            <view class="img_wrapper" @tap="chooseLocation">
              <image src="/static/address/1.png"></image>
              <text>定位</text>
            </view>
          </view>
        </u-form-item>
       <!-- <u-form-item
          label="门牌号"
          prop="houseNumber"
          class="positioning_wrapper"
        >
          <view class="content_">
            <u-input
              v-model="formData.houseNumber"
              placeholder="街道、门牌号等"
            ></u-input>
          </view>
        </u-form-item> -->
      </u-form>
    </view>
    <view class="location_acquisition">
      <view class="title_">智能识别</view>
      <!--      <view class="text_">-->
      <!--        <u-input-->
      <!--          v-model="value"-->
      <!--          :type="type"-->
      <!--          :border="border"-->
      <!--          placeholder="请输入或粘贴地址文本，可自动识别姓名、电话和地址，如：上海市宝山区长江路100号，某某，188****1234"-->
      <!--        />-->
      <!--      </view>-->
      <view class="identify_">
        <view>
          <auto-parse-address
            boxClass="c-box"
            @result="result"
            placeholder="请输入或粘贴地址文本，可自动识别姓名、电话和地址，如：上海市宝山区长江路100号，某某，188****1234"
            btnClass="but_"
            >识别</auto-parse-address
          >
        </view>
      </view>
    </view>
    <view class="switch_wrapper">
      <view>设为默认地址</view>
      <view class="switch_">
        <u-switch
          v-model="checked"
          :loading="loading"
          active-color="#FA5151"
          @change="change"
        ></u-switch>
      </view>
    </view>
    <view class="submit_wrapper">
      <view @click="submit">保存</view>
    </view>
  </view>
</template>

<script>
import { addConsigneeInfo,updateConsigneeInfo, saveAddrAdd, selAddrApi, updateAddr } from "@/api/address";
import { mapGetters } from "vuex";

export default {
  computed: mapGetters(["userId"]),
  name: "index",
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
    this.defaultRegion = ["广东省", "广州市", "天河区"];
  },
  onShow() {
    // this.addressListFn();
  },
  onLoad(options) {
	  this.savetype=options.type&&options.type==1?true:false
	  this.formData.userId= uni.getStorageSync("userId")?uni.getStorageSync("userId"):""
	  var sjs=this.randomWord()
	 var datatime = Date.parse(new Date());
	 this.formData.token=''+sjs+''+datatime
    console.log(options,'options')
    if (options&&options.address) {
      const address = JSON.parse(decodeURIComponent(options.address));
      console.log(address,'解析后的')
      //修改导航标题
      uni.setNavigationBarTitle({
        title: address && address.id ? "修改地址" : "添加收货地址",
      });

      //识别地址地区
      this.model.region =
        address.consigneeProvince + "-" + address.consigneeCity + "-" + address.consigneeArea;
      this.checked = address.defaultFlag == 0 ? true : false;
      //详情地址
      this.formData = {
        // ...this.formData,
        ...address
      };
    }else{
		this.checked = this.formData.defaultFlag == 1 ? true : false;
	
	}
  },
  watch: {
    checked(val) {
      console.log(val, "监听开关");
      // 等于false，意味着用户手动关闭了switch
      if (val == false) {
        // if (this.addressList.length === 0) {
        //   // 重新打开switch，并让它处于加载中的状态
        //   this.checked = true;
        //   this.loading = true;
        //   this.formData.defaultFlag = 0;
        //   this.getRestultFromServer();
        // }
        // if (this.controlStatus == true) {
        //   this.controlStatus = false;
        //   return;
        // }
        // 重新打开switch，并让它处于加载中的状态
        // 模拟向后端发起请求
      }
    },
  },
  data() {
    return {
      addressList: {},
      userAddress: {
        isDefault: false,
      },
      //开关
      loading: false,
      checked: false,
      // 中间变量，避免在watch中多次回调，造成无限循环
      controlStatus: false,
      //智能识别地址
      addressForm: {},
      value: "",
      border: false,
      type: "textarea",
      height: 100,
      autoHeight: true,
      pickerShow: false,
      model: {
        region: "",
      },
      rules: {
        consigneeName: [
          {
            required: true,
            message: "请输入姓名",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
        ],
        consigneeAddress: [
          {
            required: true,
            message: "请输入详情",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
        ],
        consigneeProvince: [
          {
            required: true,
            message: "请选择地区",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              console.log(value, "地区22");
              if (value == "") {
                return callback("请输入地区");
              } else {
                // 上面有说，返回true表示校验通过，返回false表示不通过
                // this.$u.test.mobile()就是返回true或者false的
                callback();
              }
            },
            message: "请选择地区",
            // 触发器可以同时用blur和change
            trigger: ["blur"],
          },
        ],
        consigneeMobile: [
          {
            required: true,
            message: "请输入正确的手机号",
            trigger: ["change", "blur"],
          },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              if (value == "") {
                return callback("请输入手机号");
              } else {
                // 上面有说，返回true表示校验通过，返回false表示不通过
                // this.$u.test.mobile()就是返回true或者false的
                return this.$u.test.mobile(value);
              }
            },
            message: "手机号码不正确",
            // 触发器可以同时用blur和change
            trigger: ["blur"],
          },
        ],
      },
      formData: {
        //用户id
        userId: "",
        //收货人
        consigneeName: "",
        //收货人手机号
        consigneeMobile: "",
        
        //省
        consigneeProvince: "",
        //城市
        consigneeCity: "",
        //区
        consigneeArea: "",
		
		//收货人地址
		consigneeAddress: "",
        //是否默认地址0默认
        defaultFlag: 1,
        //门牌号
        token: "",
      },
      //选择的地区 中午形式
      defaultRegion: [],
      areaCode: [],
	  savetype:false,
    };
	
  },
  methods: {
    async addressListFn() {
      console.log(this.userId,'this.userId')
      const res = await selAddrApi(this.userId);
      console.log(res, "`地址管理");
      if (res.code === 0) {
        this.addressList = res.data;
        if (this.addressList.length === 0) {
          this.checked = true;
          this.formData.itemType = 0;
        }
      }
    },

    //识别
    result(e) {
      console.log(e, "识别");
      if (e && e.area) {
        uni.showToast({
          title: "识别成功",
          icon: "success",
          duration: 2000,
        });
        const { province, name, city, area, detail, phone, postalCode } = e;
        //识别地址地区
        this.model.region = province + "-" + city + "-" + area;
        //详情地址
        this.formData.consigneeAddress = detail;
        //收货人手机号
        this.formData.consigneeMobile = phone;
        //收货人姓名
        this.formData.consigneeName = name;
        //地区
        this.formData.consigneeProvince = province;
        this.formData.consigneeCity = city;
        this.formData.consigneeArea = area;
      } else {
        uni.showToast({
          title: "识别失败",
          icon: "error",
          duration: 2000,
        });
      }

      /**
       * @params e: { province: '', name: '', city: '', area: '', detail: '', phone: '', postalCode: '' }
       *
       * */
    },

    //修改默认地址设置
    ChangeIsDefault: function (e) {
      this.$set(this.userAddress, "isDefault", !this.userAddress.isDefault);
    },
    //获取所在附近地址
    chooseLocation: function () {
      uni.chooseLocation({
        success: (res) => {
          if (res.address) {
            console.log(res, "地址获取定位");
            //截取地区
            const reg = /.+?(省|市|自治区|自治州|县|区)/g;

            // console.log(res.address + ": ", res.address.match(reg)[0], "地区");
            //定位后保存地区
            this.formData.consigneeProvince = res.address.match(reg)[0];
            this.formData.consigneeCity = res.address.match(reg)[1];
            this.formData.consigneeArea = res.address.match(reg)[2];
            //识别地址地区
            this.model.region =
              res.address.match(reg)[0] +
              "-" +
              res.address.match(reg)[1] +
              "-" +
              res.address.match(reg)[2];
            //
            this.$set(
              this.userAddress,
              "detail",
              res.address.replace(/.+?(省|市|自治区|自治州|县|区)/g, "")
            );
            //详细地址
            this.formData.consigneeAddress = this.userAddress.detail;
          }
        },
      });
    },

    // switch打开或者关闭时触发，值为true或者false
    change(status) {
      console.log(status, "开关");
      if (status) {
        //0 为默认地址
        this.formData.defaultFlag = 0;
      } else {
        this.formData.defaultFlag = 1;
      }
    },
    getRestultFromServer() {
      // 通过定时器模拟向后端请求
      setTimeout(() => {
        this.controlStatus = true;
        // 后端允许用户关闭switch，设置checked为false，结束loading状态
        this.loading = false;
        this.checked = true;
        uni.showToast({
          title: "不可修改!",
          icon: "error",
          duration: 2000,
        });
      }, 1500);
    },

    // 选择地区回调
    regionConfirm(e) {
      console.log(e);
      this.model.region =
        e.province.label + "-" + e.city.label + "-" + e.area.label;
      console.log(this.model.region, "地区");
      this.formData = {
        ...this.formData,
        //省
        consigneeProvince: e.province.label,
        //城市
        consigneeCity: e.city.label,
        //区
        consigneeArea: e.area.label,
      };
    },
    async submit() {
      this.$refs.uForm.validate(async (valid) => {
        if (valid) {
          console.log("验证通过");
		  console.log(this.formData)
		  // return
          // let formData = JSON.parse(JSON.stringify(this.formData));
          // if (formData.houseNumber) {
          //   formData.addr = this.formData.addr + this.formData.houseNumber;
          //   delete formData.houseNumber;
          // } else {
          //   delete formData.houseNumber;
          // }
          // console.log(formData, "保存2");
          if (this.formData.consigneeInfoId) {
			 
			 
            const res = await updateConsigneeInfo(JSON.stringify(this.formData) );
            console.log(res, "编辑接口");
            if (res.result == 0) {
              uni.showToast({
                title: "修改成功",
                icon: "success",
                duration: 2000,
              });
              uni.navigateBack({
                delta: 1,
              });
            }
          } else {
            const res = await addConsigneeInfo(JSON.stringify(this.formData) );
            console.log(res, "添加接口");
            if (res.result == 0) {
			
			 if(this.savetype){
				 let pages = getCurrentPages();//获取页面实例
				 				let nowPage = pages[pages.length - 1];//当前页面实例
				 				let prevPage = pages[pages.length - 2];//上一级页面实例
				 				let carobj = this.formData
				 				//在这个地方向上一个页面的实例的函数传递一个参数
				 				//Backcardaa函数是A页面中封装的函数
				 				prevPage.$vm.selectaddress(carobj)
				 				uni.navigateBack({
				 					delta: 1
				 				})
			 }else{
				 uni.showToast({
				   title: "添加成功",
				   icon: "success",
				   duration: 2000,
				 });
				 uni.navigateBack({
				   delta: 1,
				 });
			 }
             
            }else{
				var sjs=this.randomWord()
				var datatime = Date.parse(new Date());
				this.formData.token=''+sjs+''+datatime
				uni.showToast({
				  title: "添加失败，请重试",
				  icon: "error",
				  duration: 2000,
				});
			}
          }
        } else {
          console.log("验证失败");
          return;
        }
      });
    },
	randomWord() {
	    var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
	     var nums = "";
	      for (var i = 0; i < 20; i++) {
	      var id = parseInt(Math.random() * 61);
	      nums += chars[id]
	      }
	      return nums; 
	      },
  },
};
</script>

<style scoped lang="scss">
.address_ {
  background-color: #f5f5f5;
  padding: rpx(12);
  .form_wrapper {
    background: #ffffff;
    border-radius: rpx(5);
    padding: rpx(0) rpx(12);
    .positioning_wrapper::v-deep {
      display: flex;
      .u-form-item {
        flex: 1;
      }
      .content_ {
        display: flex;
      }
    }
    .img_wrapper {
      display: flex;
      align-items: center;
      margin-left: auto;
      > image {
        width: rpx(12);
        height: rpx(12);
        vertical-align: middle;
        //margin-top: rpx(3);
        margin-right: rpx(2);
      }
      > text {
        font-size: rpx(12);
        font-weight: 400;
        color: #353535;
      }
    }
  }
  > .location_acquisition {
    padding: rpx(16) rpx(12);
    margin-top: rpx(8);
    background: #ffffff;
    border-radius: rpx(5);
    > .text_ {
      background: #fafafa;
      border-radius: rpx(5);
      padding: rpx(12);
      margin-top: rpx(8);
    }
    > .identify_ {
      display: flex;
      margin-top: rpx(8);
      view {
        //margin-left: auto;
        //background: #fa5151;
        //border-radius: rpx(12);
        //padding: rpx(3) rpx(15);
        //font-size: rpx(13);
        //font-weight: 400;
        ////color: #ffffff;
        //margin-top: rpx(8);
      }
    }
  }
  > .switch_wrapper {
    display: flex;
    //width: rpx(351);
    //height: rpx(50);
    align-items: center;
    justify-content: space-between;
    background: #ffffff;
    margin-top: rpx(8);
    border-radius: rpx(5);
    padding: rpx(12) rpx(14) rpx(12) rpx(12);
    margin-bottom: rpx(180);
  }
  > .submit_wrapper {
    display: flex;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #ffffff;
    padding: rpx(8) rpx(12) rpx(8);
    z-index: 99;
    > view {
      background: #fa5151;
      border-radius: rpx(22);
      width: rpx(351);
      height: rpx(44);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: rpx(17);
      font-weight: 400;
      color: #ffffff;
    }
  }
}
</style>
